//
//  BTSearchView.m
//  BreadTrip
//
//  Created by Vivitickey on 2017/4/19.
//  Copyright © 2017年 test. All rights reserved.
//

#import "BTSearchView.h"
#import "DGActivityIndicatorView.h"
#import "BTSearchModel.h"
#import "Masonry.h"
#import "PTModel.h"
#import "HomeModel.h"
#import "LLWebViewController.h"
#import "EDSearchResultViewController.h"
@interface BTSearchView () <UIScrollViewDelegate>

@property (nonatomic,strong) BTSearchModel *model;
@property (nonatomic,strong) DGActivityIndicatorView * activityIndicatorView;
@end

@implementation BTSearchView
- (void)showLoadingAnimation
{
    [_activityIndicatorView startAnimating];
}
- (void)stopLoadingAnimation
{
    
    [_activityIndicatorView stopAnimating];
}
-(instancetype)initWithFrame:(CGRect)frame{
    
    if (self = [super initWithFrame:frame]) {
        
        self.backgroundColor = [UIColor whiteColor];
        _hotArray = [[NSMutableArray alloc] init];
        _allArray = [[NSMutableArray alloc] init];
        _activityIndicatorView = [[DGActivityIndicatorView alloc] initWithType:DGActivityIndicatorAnimationTypeCookieTerminator tintColor:MAINCOLOR];
        
    }
    
    return self;
    
}
- (void)setHistoryArray:(NSArray *)historyArray
{
    _historyArray = historyArray;
    [self loadData];
}
-(void)setupUI{
//    历史记录

    [_historicalBGView removeFromSuperview];
    _historyArray = [_searchVM readHistory];
    _historicalBGView  = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 0)];
    [self addSubview:_historicalBGView];
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(14, 14, 8, 8)];
    view.backgroundColor = RGBA(44, 143, 219, 1);
    KViewRadius(view, 4);
    [_historicalBGView addSubview:view];
    UILabel *historicalLabel = [[UILabel alloc]initWithFrame:CGRectMake(view.right + 5, 0, 200, 20)];
    historicalLabel.text = @"历史记录";
    historicalLabel.textColor = RGBA(68, 68, 68, 1);
    historicalLabel.font = AutoFont(14);
    historicalLabel.centerY = view.centerY;
    [_historicalBGView addSubview:historicalLabel];
     WeakSelf
    UIButton * button = [[UIButton alloc] initWithFrame:CGRectMake(_historicalBGView.width - 100, 0, 80, 30)];
    [button setImage:[UIImage imageNamed:@"delete"] forState:0];
    [button setTitle:@"删除" forState:0];
    button.titleLabel.font =AutoFont(14);
    [button setTitleColor:RGBA(68, 68, 68, 1) forState:0];
    [button centerHorizontallyImageAndTextWithPadding:6];
    button.centerY = historicalLabel.centerY;
    [button add_BtnClickHandler:^(NSInteger tag) {
        [weakSelf.searchVM deleteHistory:@""];
        [weakSelf setupUI];
    }];
    [_historicalBGView addSubview:button];
    UIView *historicalView = [self addButtonWithHistoryArray:_historyArray];
    historicalView.frame = CGRectMake(0, historicalLabel.bottom +14, UIScreenWidth , historicalView.height);
    [_historicalBGView addSubview:historicalView];
    UIView * line = [[UIView alloc] initWithFrame:CGRectMake(13, historicalView.bottom +16, UIScreenWidth -26, 0.5)];
    line.backgroundColor =RGBA(161, 161, 161, 1);
    [_historicalBGView addSubview:line];
    _historicalBGView.height = 14+8+14+ historicalView.height +17;
    _popularBGView.mj_y = _historicalBGView.bottom;
    _gamerBGView.mj_y = _popularBGView.bottom;
}
- (void)initGameUI
{
    
    
    //最近游戏
    [_gamerBGView removeFromSuperview];
    _gamerBGView =  [[UIView alloc] initWithFrame:CGRectMake(0, _historicalBGView.bottom, UIScreenWidth, 0)];
    UIView *view2 = [[UIView alloc] initWithFrame:CGRectMake(14,14, 8, 8)];
    view2.backgroundColor = RGBA(44, 143, 219, 1);
    KViewRadius(view2, 4);
    [_gamerBGView addSubview:view2];
    UILabel *gameLabel = [[UILabel alloc]initWithFrame:CGRectMake(view2.right + 5, 0, 200, 20)];
    gameLabel.text = @"最近游戏";
    gameLabel.textColor = RGBA(68, 68, 68, 1);
    gameLabel.font = AutoFont(14);
    gameLabel.centerY = view2.centerY;
    [_gamerBGView addSubview:gameLabel];
    
   
    
    UIView * gamerView = [self addButtonWithGameArray:_allArray];
    gamerView.frame = CGRectMake(0, gameLabel.bottom +14, UIScreenWidth , gamerView.height);
    [_gamerBGView addSubview:gamerView];
    
    UIView * line1 = [[UIView alloc] initWithFrame:CGRectMake(13, gamerView.bottom +16, UIScreenWidth -26, 0.5)];
    line1.backgroundColor =RGBA(161, 161, 161, 1);
    [_gamerBGView addSubview:line1];
    
    _gamerBGView.height = 14+8+20+ gamerView.height +17;
    [self addSubview:_gamerBGView];
    
    //热门游戏
    [_popularBGView removeFromSuperview];
    _popularBGView = [[UIView alloc] initWithFrame:CGRectMake(0, _gamerBGView.bottom, UIScreenWidth, 0)];
    [self addSubview:_popularBGView];
    UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(14, 14, 8, 8)];
    view1.backgroundColor = RGBA(44, 143, 219, 1);
    KViewRadius(view1, 4);
    [_popularBGView addSubview:view1];
    UILabel *popularLabel = [[UILabel alloc]initWithFrame:CGRectMake(view1.right + 5, 0, 200, 20)];
    popularLabel.text = @"热门游戏";
    popularLabel.textColor = RGBA(68, 68, 68, 1);
    popularLabel.font = AutoFont(14);
    popularLabel.centerY = view1.centerY;
    [_popularBGView addSubview:popularLabel];
    
    UIView * popularView = [self addButtonWithHotArray:_hotArray];
    popularView.frame = CGRectMake(0, popularLabel.bottom +14, UIScreenWidth , popularView.height);
    [_popularBGView addSubview:popularView];
    
   
     _popularBGView.height = 14+8+14+ popularView.height +17;
  
    
    
   
    //设置scrollView 滚动
    [self setContentSize:CGSizeMake(self.frame.size.width, _historicalBGView.height + _popularBGView.height +_gamerBGView.height +40)];
    //隐藏滚动条
    self.showsVerticalScrollIndicator = NO;
}
#pragma mark - 网络请求 -
-(void)loadData{

     [self setupUI];

//    获取热门游戏
    [self gethotGame];
}
- (void)gethotGame
{
    [self showLoadingAnimation];
    WeakSelf
    NSString  * AllGame = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"getGameHot"];
    [[SmileHttpTool sharedInstance] GET :AllGame parameters:@{} origin:YES success:^(NSInteger statusCode, NSString *message, id responseObject) {
        NSDictionary * dict = [WJUnit dictionaryWithJsonString:responseObject];
        if ([[dict jsonString:@"statusCode"] isEqualToString:@"SUCCESS"]) {
            NSDictionary * dic = [self objectFromJSONString:responseObject];
            self.hotArray  = [PTModel mj_objectArrayWithKeyValuesArray:dic[@"data"]];
            
            
            if (![DJLoginHelper sharedInstance].is_Login)
            {
               [weakSelf initGameUI];
                [weakSelf stopLoadingAnimation];
            }else
            {
                [weakSelf getAllGame];
            }
//
        }else{
            [JMNotifyView showNotify:[dict jsonString:@"message"]  isSuccessful:NO];
        }
       
        
    } failure:^(id responseObject, NSError *error) {
        [weakSelf stopLoadingAnimation];
        
    }];
}
- (void)getAllGame
{
    WeakSelf
    NSString  * AllGame = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"getUserLatelyGame"];
    [[SmileHttpTool sharedInstance] GET :AllGame parameters:@{} origin:YES success:^(NSInteger statusCode, NSString *message, id responseObject) {
        NSDictionary * dict = [WJUnit dictionaryWithJsonString:responseObject];
        if ([[dict jsonString:@"statusCode"] isEqualToString:@"SUCCESS"]) {
            NSDictionary * dic = [self objectFromJSONString:responseObject];
            self.allArray  = [LatelyModel mj_objectArrayWithKeyValuesArray:dic[@"data"]];
            [self initGameUI];

        }else{
             [self initGameUI];
            [JMNotifyView showNotify:[dict jsonString:@"message"]  isSuccessful:NO];
        }
        [self stopLoadingAnimation];

    } failure:^(id responseObject, NSError *error) {
         [weakSelf getAllGame];

    }];
}

#pragma mark - button创建方法 -
//循环创建Button
-(UIView *)addButtonWithHistoryArray:(NSArray *)historyArray{
    
    
    UIView *SearchButtonView = [[UIView alloc]init];
    SearchButtonView.tag =10086;
    CGFloat w = 0;//保存前一个button的宽以及前一个button距离屏幕边缘的距离
    CGFloat h = 0;
    CGFloat button_h = 0;
    for (int i = 0; i < historyArray.count; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        [button addTarget:self action:@selector(history:) forControlEvents:UIControlEventTouchUpInside];
        button.tag = i;
        button.backgroundColor = [UIColor clearColor];
        [button setTitleColor:MAINCOLOR forState:UIControlStateNormal];
        button_h = 30;
        button.titleLabel.font = AutoFont(14);
        //根据计算文字的大小
        NSDictionary *attributes = @{NSFontAttributeName:AutoFont(14)};
        CGFloat length = [historyArray[i] boundingRectWithSize:CGSizeMake(self.frame.size.width, 2000) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size.width;
        //为button赋值
        [button setTitle:historyArray[i] forState:UIControlStateNormal];
        //当button的位置超出屏幕边缘时换行  只是button所在父视图的宽度
        if(20 + w + length + 30 > self.frame.size.width){
            w = 0; //换行时将w置为0
            h = h + 34;//距离父视图也变化
            button.frame = CGRectMake(20 + w, h, length + 20, button_h);//重设button的frame
        }else{
            //设置button的frame
            button.frame = CGRectMake(20 + w, h, length + 20 , button_h);
            
        }
       
        w = button.frame.size.width + button.frame.origin.x;
        [SearchButtonView addSubview:button];
    }
    if (historyArray.count>0)
    {
         SearchButtonView.frame = CGRectMake(0, 0, self.frame.size.width, h+30);
    }else
    {
         SearchButtonView.frame = CGRectMake(0, 0, self.frame.size.width, h);
    }
   
    
    return SearchButtonView;
    
}
//循环创建Button
-(UIView *)addButtonWithHotArray:(NSArray *)hotArray{
    
    
    UIView *SearchButtonView = [[UIView alloc]init];
     SearchButtonView.tag =10000;
    CGFloat w = 0;//保存前一个button的宽以及前一个button距离屏幕边缘的距离
    CGFloat h = 0;
    CGFloat button_h = 0;
    for (int i = 0; i < hotArray.count; i++) {
        PTModel * model = hotArray[i];
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        
        [button addTarget:self action:@selector(hotClick:) forControlEvents:UIControlEventTouchUpInside];
        button.tag =100 + i;
        button.backgroundColor = RandColor;
        [button setTitleColor:WHITECOLOR forState:UIControlStateNormal];
        button_h = 26;
        button.titleLabel.font = AutoFont(14);
        KViewRadius(button, 2);
        //根据计算文字的大小
        NSDictionary *attributes = @{NSFontAttributeName:AutoFont(14)};
        CGFloat length = [model.displayname boundingRectWithSize:CGSizeMake(self.frame.size.width, 2000) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size.width;
        //为button赋值
        [button setTitle:model.displayname forState:UIControlStateNormal];
        
        //当button的位置超出屏幕边缘时换行  只是button所在父视图的宽度
        if(20 + w + length + 30 > self.frame.size.width){
            w = 0; //换行时将w置为0
            h = h + 34;//距离父视图也变化
            button.frame = CGRectMake(20 + w, h, length + 20, button_h);//重设button的frame
        }else{
            //设置button的frame
            button.frame = CGRectMake(20 + w, h, length + 20 , button_h);
            
        }
        
        w = button.frame.size.width + button.frame.origin.x;
        [SearchButtonView addSubview:button];
    }
    if (hotArray.count>0)
    {
        SearchButtonView.frame = CGRectMake(0, 0, self.frame.size.width, h+30);
    }else
    {
        SearchButtonView.frame = CGRectMake(0, 0, self.frame.size.width, h);
    }
    
    return SearchButtonView;
    
}
//循环创建Button
-(UIView *)addButtonWithGameArray:(NSArray *)arr{


    UIView *SearchButtonView = [[UIView alloc]init];
    SearchButtonView.tag =10000;
    CGFloat w = 0;//保存前一个button的宽以及前一个button距离屏幕边缘的距离
    CGFloat h = 0;
    CGFloat button_h = 0;
    
    for (int i = 0; i < arr.count; i++) {
        LatelyModel * model = arr[i];
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        
        [button addTarget:self action:@selector(GameClick:) forControlEvents:UIControlEventTouchUpInside];
        button.tag =1000 + i;
        button.backgroundColor = RandColor;
        [button setTitleColor:WHITECOLOR forState:UIControlStateNormal];
        button_h = 26;
        button.titleLabel.font = AutoFont(14);
        KViewRadius(button, 2);
        //根据计算文字的大小
        NSDictionary *attributes = @{NSFontAttributeName:AutoFont(14)};
        CGFloat length = [model.displayname boundingRectWithSize:CGSizeMake(self.frame.size.width, 2000) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size.width;
        //为button赋值
        [button setTitle:model.displayname forState:UIControlStateNormal];
        
        //当button的位置超出屏幕边缘时换行  只是button所在父视图的宽度
        if(20 + w + length + 30 > self.frame.size.width){
            w = 0; //换行时将w置为0
            h = h + 34;//距离父视图也变化
            button.frame = CGRectMake(20 + w, h, length + 20, button_h);//重设button的frame
        }else{
            //设置button的frame
            button.frame = CGRectMake(20 + w, h, length + 20 , button_h);
            
        }
        
        w = button.frame.size.width + button.frame.origin.x;
        [SearchButtonView addSubview:button];
    }
    if (arr.count>0)
    {
        SearchButtonView.frame = CGRectMake(0, 0, self.frame.size.width, h+30);
    }else
    {
        SearchButtonView.frame = CGRectMake(0, 0, self.frame.size.width, h);
    }


    return SearchButtonView;

}
// 最近游戏
- (void)GameClick:(UIButton *)sender
{
    LatelyModel * model =  _allArray[sender.tag-1000];
    [self showLoadingAnimation];
    NSString  * game = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"getGameUrl"];
    NSDictionary * parame = @{@"mode":@"online",@"gameid":model.gameid,@"plat_id":model.plat_id,@"gamecode":model.gamecode};
    [[SmileHttpTool sharedInstance] GET :game parameters:parame origin:YES success:^(NSInteger statusCode, NSString *message, id responseObject){
        [self stopLoadingAnimation];
        NSDictionary * dic = [self objectFromJSONString:responseObject];
        if ([dic[@"statusCode"] isEqual:@"SUCCESS"]) //请求成功
        {
            LLWebViewController * webview = [[LLWebViewController alloc] init];
            webview.urlStr = dic[@"data"];
            if ([WJUnit allowRotationWithGameid:model.gameid])
            {
                webview.isType = 2;
            }else
            {
                webview.isType = 3;
            }
            webview.isShowGame = YES;
            [ [WJUnit currentViewController].navigationController pushViewController:webview animated:YES];
        }else
        {
            [JMNotifyView showNotify:[dic jsonString:@"message"]  isSuccessful:NO];
        }
        
        
    } failure:^(id responseObject, NSError *error) {
        [self stopLoadingAnimation];
        [WJUnit showMessage:@"请求错误"];
        
    }];
}

// 点击搜索游戏
- (void)history:(UIButton *)btn{
    NSLog(@"-->%@",_historyArray);
    EDSearchResultViewController * searchVC = [[EDSearchResultViewController alloc] init];
    searchVC.name = _historyArray[btn.tag];
    searchVC.searchVM = _searchVM;
    [[WJUnit currentViewController].navigationController pushViewController:searchVC animated:YES];
}
//热门
- (void)hotClick:(UIButton *)btn
{
    PTModel * model =  _hotArray[btn.tag -100];
    [self getGameURLWithModel:model editInfo:@"online"];
    
}
- (void)getGameURLWithModel:(PTModel *)model editInfo:(NSString *)editInfo
{
    [self showLoadingAnimation];
    NSString  * game = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"getGameUrl"];
    NSDictionary * parame = @{@"mode":editInfo,@"gameid":model.gameid,@"plat_id":model.plat_id,@"gamecode":model.gamecode};
    [[SmileHttpTool sharedInstance] GET :game parameters:parame origin:YES success:^(NSInteger statusCode, NSString *message, id responseObject){
        [self stopLoadingAnimation];
        NSDictionary * dic = [self objectFromJSONString:responseObject];
        if ([dic[@"statusCode"] isEqual:@"SUCCESS"]) //请求成功
        {
            LLWebViewController * webview = [[LLWebViewController alloc] init];
             webview.urlStr = dic[@"data"];
            if (model.orientation.integerValue ==2)
            {
                webview.isType = 2;
            }else
            {
                webview.isType = 3;
            }
            webview.isShowGame = YES;
            [ [WJUnit currentViewController].navigationController pushViewController:webview animated:YES];
        }else
        {
            [JMNotifyView showNotify:[dic jsonString:@"message"]  isSuccessful:NO];
        }
        
        
    } failure:^(id responseObject, NSError *error) {
        [self stopLoadingAnimation];
        [WJUnit showMessage:@"请求错误"];
        
    }];
}
@end
